import WebHeader from '@/www/components/WebHeader'
import WebFooter from '@/www/components/WebFooter'
import { getQuote, uploadFile, postQuoteOrder } from '@/apiv2/quote'

const CODE = 'Envelope'

export default {
  components: { WebHeader, WebFooter },
  data() {
    return {
      quoteData: undefined,
      checkValue: {

      },

      quoteValue: {
        category: undefined,
        color: undefined,
        customQuantity: undefined,
        style: 1,
        quantity: undefined,
        size: undefined,
        customLength: undefined,
        customWidth: undefined
      },
      customSize:false,
      user: undefined,
      quote: undefined,
      quoteList: undefined,
      detail: undefined,
      fileList: [],
      postData: {
        quantity: undefined,
        detail: undefined,
        amount: undefined,
        fileIds: undefined
      },
      note: undefined
    }
  },

  created(){
    const user = JSON.parse(localStorage.getItem('user'))
    this.user = user

    getQuote(CODE).then(res => {
      let quoteData = res.config
      this.quoteValue.category = quoteData.cateData.list[0]
      this.quoteValue.size = quoteData.sizeData.list[0]
      this.quoteValue.color = quoteData.colorData.list[0]
      this.quoteValue.quantity = quoteData.stepData.list[0]
      this.quoteData = quoteData
    })
  },

  methods: {

    getQuote(){
      let detail = ''
      let {customSize,quoteData,quoteValue,checkValue,postData} = this

      if(customSize && (!quoteValue.customLength || !quoteValue.customWidth)){
        this.$message.error('请输入自定义尺寸')
        return
      }

      let finalQantity = quoteValue.quantity ? parseInt(quoteValue.quantity) : parseInt(quoteValue.customQuantity)
      detail += finalQantity + quoteData.param.unit

      let length = undefined
      let width = undefined
      if(quoteValue.customLength && quoteValue.customWidth && customSize){
        length = parseInt(quoteValue.customLength)
        width = parseInt(quoteValue.customWidth)
      }else if(quoteValue.size){
        let sizeStr = quoteValue.size.match(/\d+\*\d+/)[0]
        length = parseInt(sizeStr.split('*')[0])
        width = parseInt(sizeStr.split('*')[1])
      }
      let {long,short} = this.findLongAndShort(length,width)
      let matchResult = this.matchSizePerCount(long,short)

      detail += quoteValue.category +'，'
        + '尺寸' + long + '*' + short +'，'
        + quoteValue.style + '款，'

      let matchQuantity = this.matchStep(Math.ceil(finalQantity/matchResult.countPerPage))

      console.log(matchResult)
      console.log(matchQuantity)

      let quoteList = []

      let defaultFlag = false

      let stepList = []

      postData.detail = detail

      quoteData.stepData.list.forEach(i => {
        const QTY = parseInt(i)//阶梯数量
        stepList.push(QTY)

        let priceItem = undefined
        for(let i=0;i<quoteData.skuList.length;i++){
          let item = quoteData.skuList[i]
          if(item.name == quoteValue.category && QTY == parseInt(item.quantity)
            && item.size == quoteValue.size && item.color == quoteValue.color){
            priceItem = item
          }
        }

        const MATERIAL_AMOUNT = parseInt(priceItem.price) * parseInt(quoteValue.style)

        let processAmount = 0

        processAmount = parseInt(processAmount) * parseInt(quoteValue.style)

        const AMOUNT = parseInt(MATERIAL_AMOUNT) + processAmount


        if(matchQuantity == parseInt(i)){
          postData.amount = AMOUNT
          defaultFlag = true
        }

        quoteList.push({
          quantity: QTY,
          materialAmount: parseInt(MATERIAL_AMOUNT),
          processAmount: parseInt(processAmount),
          totalAmount: AMOUNT

        })

        this.quoteList = quoteList
      })

      if(!defaultFlag){
        let target = parseInt(finalQantity)
        let farr = []
        for(let i=(stepList.length-1);i > -1;i--){
          if(target < stepList[i]){
            continue
          }
          let m = target % stepList[i]
          farr.push({
            quantity: stepList[i],
            count: parseInt(target / stepList[i])
          })
          if(m == 0){
            break
          }else{
            target = m
          }
        }

        let finalMaterialAmount = 0
        let finalProcessAmount = 0
        let index = undefined
        for(let i=0;i<quoteList.length;i++){
          let item = quoteList[i]
          for(let j=0;j<farr.length;j++){
            if(item.quantity == farr[j].quantity){
              if(!index){
                index = i
              }
              finalMaterialAmount += item.materialAmount * farr[j].count
              finalProcessAmount += item.processAmount * farr[j].count
            }
          }
        }
        quoteList.splice(index + 1,0,{
          quantity: finalQantity,
          materialAmount: parseInt(finalMaterialAmount),
          processAmount: parseInt(finalProcessAmount),
          totalAmount: parseInt(finalMaterialAmount) + parseInt(finalProcessAmount)
        })
        postData.amount = parseInt(finalMaterialAmount) + parseInt(finalProcessAmount)
        this.quoteList = quoteList
        this.postData = postData
      }

    },

    //匹配最终出纸尺寸和单张拼数
    matchSizePerCount(length,width){
      let sizeList = this.quoteData.sizeData.list

      //小于最小尺寸，按最小尺寸拼1个
      let minLong = parseInt(this.quoteData.param.minSize.split('*')[0])
      let minShort = parseInt(this.quoteData.param.minSize.split('*')[1])
      if(length <= minLong && width <= minShort){
        return {
          size: this.quoteData.sizeData.list[0],
          countPerPage: 1
        }
      }

      for(let i = 0; i < sizeList.length; i++){
        let sizeStr = sizeList[i].match(/\d+\*\d+/)[0]
        let l = parseInt(sizeStr.split('*')[0])
        let w = parseInt(sizeStr.split('*')[1])
        let {long,short} = this.findLongAndShort(l,w)
        if(length <= long && width <= short){
          return {
            size: sizeList[i],
            countPerPage: parseInt(long/length) * parseInt(short/width)
          }
        }
      }
      return undefined
    },

    //匹配数量阶梯
    matchStep(quantity){
      let returnQuantity = undefined
      let list = this.quoteData.stepData.list
      for(let i = 0; i < list.length; i++){
        if(quantity <= parseInt(list[i])){
          returnQuantity = parseInt(list[i])
          break
        }
      }
      return returnQuantity
    },

    //确认长边短边
    findLongAndShort(l,w){
      return {
        long: l >= w ? l : w,
        short: w <= l ? w : l
      }
    },

    //判断输入尺寸是否系小于或者等于指定尺寸
    checkIsLessOrEqualThanTargetSize(length,width,targetLength,targetWidth){
      let flag = false
      let long = undefined
      let short = undefined
      if(length >= width){
        long = length
        short = width
      }else{
        long = width
        short = length
      }

      if((long <= 420 && short <= 285) || (long <= 570 && short <= 210)){
        flag = true
      }

      return flag
    },


    //自定义尺寸切换
    onCustomSizeToggle(){
      this.quoteValue.customLength = undefined
      this.quoteValue.customWidth = undefined
    },

    selectQuantity(){
      if(this.quoteValue.quantity){
        this.quoteValue.customQuantity = undefined
      }
    },
    customQuantity(){
      if(this.quoteValue.customQuantity){
        this.quoteValue.quantity = undefined
      }else{
        this.quoteValue.quantity = this.quoteData.stepData.list[0]
      }
    },

    syncCheck(name,target){
      if(this.checkValue[name]){
        this.checkValue[target] = true
      }
    },

    offCheck(name,target){
      if(!this.checkValue[name]){
        this.checkValue[target] = false
      }
    },

    submitOrder(){
      const {fileList,postData} = this

      if(fileList.length < 1){
        this.$message.error('请上传设计稿')
        return
      }

      let fileIds = [];
      fileList.forEach(item => {
        fileIds.push(item.id)
      })
      postData.fileIds = fileIds

      const loading = this.$loading({
        lock: true,
        text: '正在创建订单',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.7)'
      });

      postQuoteOrder(postData).then(res => {
        loading.close()
        this.$message.success('成功创建订单')
        this.$router.push({
          path: '/submitOrder',
          query: { id : res.id}
        })
      }).catch(err => {
        loading.close()
        this.$message.error('创建订单失败')
      })
    },

    handleUpload: async function(data){
      const formData = new FormData()
      formData.append('file', data.file)
      const res = await uploadFile(formData)
      let fileList = this.fileList
      fileList.push(res.file)
      this.fileList = fileList
      console.log(fileList)
    },
  }
}
